package com.itheima;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisMessageConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Reference
    OrderService orderService;
    @Autowired
    JedisPool jedisPool;
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map<String,String> map){
        try {
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            String telephone= map.get("telephone");
            String validCode = jedisPool.getResource().get(RedisMessageConst.SENDTYPE_ORDER+"-"+telephone);
            String validateCode = map.get("validateCode");
            System.out.println(validateCode);
            System.out.println(validCode);
            if (validCode!=null&&validCode.equals(validateCode)){
               Result result= orderService.addOrder(map);
               return result;
            }else {
                return new Result(false, MessageConst.VALIDATECODE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ORDER_FAIL);
        }


    }
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map<String,Object> map= orderService.findById(id);
            Date orderDate1 =(Date) map.get("orderDate");
            String orderDate = new SimpleDateFormat("yyyy-MM-dd").format(orderDate1);
            map.put("orderDate",orderDate);
            return new Result(true,MessageConst.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_ORDER_FAIL);
        }

    }
}
